package org.porridge.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.text.*;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.porridge.module.util.po.Setting;
import org.transmit.ActionContext;
import org.transmit.util.FileUtil;

public class BaseUtil
{
	/**
	 * 对数进行补位 
	 * @param code 
	 * @param num
	 * @return
	 */
	public static String formatCode(String code,int num){
		  String retcode=null;
		  NumberFormat formatter = NumberFormat.getNumberInstance();   
		  formatter.setMinimumIntegerDigits(num);   
		  formatter.setGroupingUsed(false);
		  if(code!=null && code.matches("\\d*")){
			  if(code.length()>num)
				  code=code.substring(code.length()-num,code.length());
			  int number=Integer.valueOf(code);
			  number+=1;
			  retcode=formatter.format(number);
		  }else{
			  retcode=formatter.format(1);
		  }
		  return  retcode;
	}
	/**
	 * 首字母转大写
	 * @param str
	 * @return
	 */
	public static String top1UpperCase(String str){
		if(str!=null && str.trim().length()>1){
			str=str.trim();
			String t1=str.substring(0,1);
			if(t1.matches("[a-zA-Z]*")){//正则判断纯字母
				t1=t1.toUpperCase();
			}
			return t1+str.substring(1,str.length());
		}else{
			return str;
		}
	}
	/**
	 * 首字母转小写
	 * @param str
	 * @return
	 */
	public static String top1LowerCase(String str){
		if(str!=null && str.trim().length()>1){
			str=str.trim();
			String t1=str.substring(0,1);
			if(t1.matches("[a-zA-Z]*")){//正则判断纯字母
				t1=t1.toLowerCase();
			}
			return t1+str.substring(1,str.length());
		}else{
			return str;
		}
	}
	
	public static void print(boolean ret){
		print(ret,null,null);
	}
	public static void print(boolean ret,String text){
		print(ret,text,null);
	}
	/**
	 * 传入html然后转义出来。。
	 * @param html
	 * @return
	 */
	public static String rethtml(String html){
		html=html.replaceAll("<","&lt;");
		html=html.replaceAll("\"","&quot;");
		html=html.replaceAll(">","&gt;");
		html=html.replaceAll("'","&#39;");
		html=html.replaceAll("\n","<br/>");
		return html;
	}
	public static void print(boolean ret,String text,String key){
			PrintWriter out=ActionContext.getPrintWriter();
			StringBuffer stb=new StringBuffer();
			stb.append("{\"result\":"+ret);
			if(text!=null && text.trim().length()!=0){
				stb.append(",\"text\":\""+BaseUtil.replaceJSON(text)+"\"");
			}
			if(key!=null && key.trim().length()!=0){
				stb.append(","+key);
			}
			stb.append("}");
			out.print(stb.toString());
			out.close();
	}
	public static String retprint(boolean ret){return retprint(ret,null,null);}
	public static String retprint(boolean ret,String text){return retprint(ret,text,null);}
	public static String retprint(boolean ret,String text,String key){
			StringBuffer stb=new StringBuffer();
			stb.append("{\"result\":"+ret);
			if(text!=null && text.trim().length()!=0){
				stb.append(",\"text\":\""+BaseUtil.replaceJSON(text)+"\"");
			}
			if(key!=null && key.trim().length()!=0){
				stb.append(","+key);
			}
			stb.append("}");
			return stb.toString();
	}
	
	public static String replaceJSON(String json){
		if(json==null || json.length()<1)return "";
		json=json.replaceAll("\"","");
		json=json.replaceAll("'","");
		json=json.replaceAll("	","");
		json=json.replaceAll("\"","");
		json=json.replaceAll("	","");
		json=json.replaceAll("\\n","");
		json=json.replaceAll("\\r","<br/>");
		return json;
	}
	/**
	 * 读取配置文件
	 * @return
	 */
	public static Setting findSetting(){
		Setting setting=new Setting();
		try{
			SAXReader reader = new SAXReader();
			File file=new File(FileUtil.URL+"setting.xml");
			if(!file.exists())file.createNewFile();
			Document document = reader.read(file);
			Element rootElement = document.getRootElement();
			for (Iterator i = rootElement.elementIterator(); i.hasNext();) {//获得根节点下的最大节点数，并循环。
				Element element = (Element) i.next();
				Field fld=setting.getClass().getDeclaredField(element.getName());
				if(fld!=null){
					fld.setAccessible(true);
					fld.set(setting,element.getText().trim());
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return setting;
	}
	/**
	 * 保存配置文件
	 * @return
	 * @throws IllegalAccessException 
	 * @throws IllegalArgumentException 
	 */
	public static boolean saveSetting(Setting sys){
		boolean bl=false;
		Document docu=DocumentHelper.createDocument();
		docu.setXMLEncoding("UTF-8");
		Element elem=docu.addElement("Setting");//最外层
		try {
			Field[] fds=sys.getClass().getDeclaredFields();
			for(Field f:fds){
				f.setAccessible(true);
				elem.addElement(f.getName()).addText(f.get(sys).toString().trim());
			}
			File file=new File(FileUtil.URL+"setting.xml");
			if(!file.exists())file.createNewFile();
			
			FileOutputStream out=new FileOutputStream(file);
			OutputFormat format=OutputFormat.createPrettyPrint();
			XMLWriter write=new XMLWriter(out,format);
			write.write(docu);
			write.close();
			bl=true;
		} catch (Exception e) { 
			e.printStackTrace();
		}
		return bl;
	}
	/**
	 * 校正日期。把类似于 
	 * 1990.1.1 	1990年1月1日		1990/1/1
	 * @param date
	 * @return
	 */
	public final static String correctionDate(String date){
		String ret=null;
		if(date!=null){
			String type=null;
			if(date.indexOf("-")!=-1)
				type="yyyy-MM-dd";
			else if(date.indexOf("年")!=-1 && date.indexOf("月")!=-1)
				type="yyyy年MM月dd";
			else if(date.indexOf("年")!=-1 && date.indexOf("月")!=-1 && date.indexOf("日")!=-1)
				type="yyyy年MM月dd日";
			else if(date.indexOf(".")!=-1)
				type="yyyy.MM.dd";
			else if(date.indexOf("/")!=-1)
				type="yyyy/MM/dd";
			if(type!=null){
				ret=BaseUtil.convertDate(BaseUtil.convertDate(date,type),"yyyy-MM-dd");
			}
		}
		return ret;
	}

	// 日志分类管理 对应log.lmodule end
	/** 
     * 返回一个32位的UUID 
     *  
     * @return 
     */  
    public final static String getUUID() {
        return String.valueOf(UUID.randomUUID()).replace("-", "");  
    }  
  
    /** 
     * 把时间转换成字符串 
     *  
     * @param date 
     * @return 
     */  
    public final static String convertDate(Date date) {  
        String value = "";  
        if (date != null) {  
            SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
            value = sim.format(date);  
        }  
        return value;  
    }  
  
    /** 
     * 计算时间差。返回分钟数 
     *  
     * @param max 
     *            最大时间 
     * @param min 
     *            最小时间 
     * @return 
     */  
    public final static int dateDifference(Date max, Date min) {  
        int count = 0;  
        if (max != null && min != null) {  
            try {  
                long diff = max.getTime() - min.getTime();  
                count = (int) (diff / (1000 * 60));  
            } catch (Exception e) {  
                e.printStackTrace();  
            }  
        }  
        return count;  
    }  
    /** 
     * 用来判断是否是数字 
     */  
    public final static boolean judgeFigure(String temp){  
        return temp.matches("[\\d]*");  
    }  
  
    /** 
     * 换时间转换为字符串。按传过来的格式转 
     *  
     * @param date 
     * @param cls 
     * @return 
     */  
    public final static String convertDate(Date date, String cls) {  
        String value = "";  
        if (date != null && cls != null && cls.trim().length() != 0) {  
            SimpleDateFormat sim = new SimpleDateFormat(cls);  
            value = sim.format(date);  
        }  
        return value;  
    }  
  
    /** 
     * 换字符串强制转换为时间 
     *  
     * @param value 
     * @return 
     */  
    public final static Date convertDate(String value) {  
        Date date = null;  
        if (value != null && value.trim().length() != 0) {  
            SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd hh:mm");  
            try {  
                date = sim.parse(value);  
            } catch (ParseException e) {  
                System.out.println("转换时间出现错误");  
                e.printStackTrace();  
            }  
        }  
        return date;  
    }  
  
    /** 
     * 将字符串强制转换为时间类型 并且传过转换的样式 如：yyyy-MM-dd hh:mm 
     *  
     * @param value 
     * @param cls 
     * @return 
     */  
    public final static Date convertDate(String value, String cls) {  
        Date date = null;  
        if (value != null && value.trim().length() != 0 && cls != null  
                && cls.trim().length() != 0) {  
            SimpleDateFormat sim = new SimpleDateFormat(cls);  
            try {  
                date = sim.parse(value);  
            } catch (ParseException e) {  
                System.out.println("转换时间出现错误");  
                e.printStackTrace();  
            }  
        }  
        return date;  
    }  
    /** 
     * 时间减法 
     * @param oldDate 
     * @param i 
     * @return 
     */  
    public final static Date DateAdd(Date date, int i) {  
        i-=i*2;  
        java.text.SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");  
        Calendar calendar = Calendar.getInstance();  
        calendar.setTime(date);  
        calendar.add(Calendar.DAY_OF_MONTH, i);// 在天上加i  
        return calendar.getTime();  
    } 
}
